package com.kouxin.appaccount.appuser;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.kouxin.appaccount.developer.Developer;
import com.kouxin.appaccount.developer.DeveloperDao;
import com.kouxin.appaccount.software.PricingStrategy;
import com.kouxin.appaccount.software.PricingStrategyDao;
import com.kouxin.appaccount.software.Software;
import com.kouxin.appaccount.software.SoftwareDao;
import com.kouxin.appaccount.trade.Trade;
import com.kouxin.appaccount.trade.TradeDao;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AppUserAction extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = -5316917962092484977L;

	private AppUser appuser;
	private AppUserDao appuserDao;
	private Software software;
	private SoftwareDao softwareDao;
	private Developer developer;
	private DeveloperDao developerDao;

	private List<PricingStrategy> pricingStrategys;
	private PricingStrategy pricingStrategy;
	private PricingStrategyDao pricingStrategyDao;
	
	private Trade trade;
	private TradeDao tradeDao;
	private List<Trade> trades;
	
	private List<AppuserSoftwareBalance> appuserSoftwareBalances;
	private AppuserSoftwareBalanceDao appuserSoftwareBalanceDao;

	private Map<String, Object> session;
	
	private String confirmPassword;
	
	public String register() throws Exception {
		AppUser example = new AppUser();
		example.setUsername(appuser.getUsername());
		if (!appuserDao.findByExample(example).isEmpty()) {
			this.addFieldError("appuser.username", "该用户名已经注册过 ");
			return INPUT;
		}
		appuserDao.insert(appuser);
		return SUCCESS;
	}
	
	public String login() throws Exception {
		AppUser appuser = appuserDao.login(this.appuser);
		if (appuser != null) {
			session.put(AppUserAuthenticationInterceptor.APPUSER_SESSION_KEY, appuser);
			return SUCCESS;
		} else {
			this.addActionError("你的用户名和密码不符，请再试一次");
			return INPUT;
		}
	}
	
	public String orderapp() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String softwareId = request.getParameter("software.id");
		if (softwareId == null || softwareId.trim().length() == 0) {
			return "preorderapp";
		}
		software = softwareDao.get(softwareId);
		if (software == null) {
			this.addActionError("找不到要购买的软件");
			request.setAttribute("redirect", request.getContextPath() + "/appuser/applist");
			return ERROR;
		} else {
			PricingStrategy pricingStrategy = new PricingStrategy();
			pricingStrategy.setSoftwareId(software.getId());
			this.pricingStrategys = pricingStrategyDao.findByExample(pricingStrategy);
			this.developer = developerDao.get(software.getDeveloperId());
			return INPUT;
		}
	}
	
	public String buyapp() throws Exception {
		try {
			appuser = (AppUser) session.get(AppUserAuthenticationInterceptor.APPUSER_SESSION_KEY);
			pricingStrategy = pricingStrategyDao.get(pricingStrategy.getId());
			software = softwareDao.get(pricingStrategy.getSoftwareId());
			developer = developerDao.get(software.getDeveloperId());
			Date tradeTime = Calendar.getInstance().getTime();
			trade = new Trade();
			trade.setAppUser(appuser);
			trade.setSoftware(software);
			trade.setDeveloper(developer);
			trade.setPricingStrategy(pricingStrategy);
			trade.setTradeTime(tradeTime);
			trade.setPaySuccess(false);
			tradeDao.insert(trade);
			
			AppuserSoftwareBalance appuserSoftwareBalance = new AppuserSoftwareBalance();
			appuserSoftwareBalance.setAppUser(appuser);
			appuserSoftwareBalance.setSoftware(software);
			appuserSoftwareBalances = appuserSoftwareBalanceDao.findByExample(appuserSoftwareBalance);
			if (appuserSoftwareBalances != null && appuserSoftwareBalances.iterator().hasNext()) {
				appuserSoftwareBalance = appuserSoftwareBalances.iterator().next();
				if ("T".equals(software.getPricingStrategyType())) {
					//更新最后期限
					Calendar expire = Calendar.getInstance();
					if (expire.getTime().before(appuserSoftwareBalance.getExpire())) {
						expire.setTime(appuserSoftwareBalance.getExpire());
					}
					if ("M".equals(pricingStrategy.getUnit())) {
						expire.add(Calendar.MONTH, pricingStrategy.getAmount().intValue());
					} else if ("D".equals(pricingStrategy.getUnit())) {
						expire.add(Calendar.DAY_OF_YEAR, pricingStrategy.getAmount().intValue());
					}
					appuserSoftwareBalance.setExpire(expire.getTime());
					appuserSoftwareBalanceDao.update(appuserSoftwareBalance);
				}
			} else {
				if ("T".equals(software.getPricingStrategyType())) {
					//设置最后期限
					Calendar expire = Calendar.getInstance();
					if ("M".equals(pricingStrategy.getUnit())) {
						expire.add(Calendar.MONTH, pricingStrategy.getAmount().intValue());
					} else if ("D".equals(pricingStrategy.getUnit())) {
						expire.add(Calendar.DAY_OF_YEAR, pricingStrategy.getAmount().intValue());
					}
					appuserSoftwareBalance.setExpire(expire.getTime());
					appuserSoftwareBalanceDao.insert(appuserSoftwareBalance);
				}
			}
		} catch (NullPointerException e) {
			this.addActionError("找不到指定的信息");
			HttpServletRequest request = ServletActionContext.getRequest();
			request.setAttribute("redirect", request.getContextPath() + "/appuser/applist");
			return ERROR;
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String tradehistory() throws Exception {
		session = (Map<String, Object>) ActionContext.getContext().get(ActionContext.SESSION);
		appuser = (AppUser) session.get(AppUserAuthenticationInterceptor.APPUSER_SESSION_KEY);
		trade = new Trade();
		trade.setAppUser(appuser);
		trades = tradeDao.findByExample(trade);
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String boughtapp() throws Exception {
		session = (Map<String, Object>) ActionContext.getContext().get(ActionContext.SESSION);
		appuser = (AppUser) session.get(AppUserAuthenticationInterceptor.APPUSER_SESSION_KEY);
		AppuserSoftwareBalance appuserSoftwareBalance = new AppuserSoftwareBalance();
		appuserSoftwareBalance.setAppUser(appuser);
		appuserSoftwareBalances = appuserSoftwareBalanceDao.findByExample(appuserSoftwareBalance);
		return SUCCESS;
	}
	
	public AppUser getAppuser() {
		return appuser;
	}

	public void setAppuser(AppUser appuser) {
		this.appuser = appuser;
	}

	public AppUserDao getAppuserDao() {
		return appuserDao;
	}

	public void setAppuserDao(AppUserDao appuserDao) {
		this.appuserDao = appuserDao;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}
	
	public Software getSoftware() {
		return software;
	}

	public void setSoftware(Software software) {
		this.software = software;
	}

	public SoftwareDao getSoftwareDao() {
		return softwareDao;
	}

	public void setSoftwareDao(SoftwareDao softwareDao) {
		this.softwareDao = softwareDao;
	}
	
	public Developer getDeveloper() {
		return developer;
	}

	public void setDeveloper(Developer developer) {
		this.developer = developer;
	}

	public DeveloperDao getDeveloperDao() {
		return developerDao;
	}

	public void setDeveloperDao(DeveloperDao developerDao) {
		this.developerDao = developerDao;
	}

	public PricingStrategyDao getPricingStrategyDao() {
		return pricingStrategyDao;
	}

	public void setPricingStrategyDao(PricingStrategyDao pricingStrategyDao) {
		this.pricingStrategyDao = pricingStrategyDao;
	}
	
	public List<PricingStrategy> getPricingStrategys() {
		return pricingStrategys;
	}

	public void setPricingStrategys(List<PricingStrategy> pricingStrategys) {
		this.pricingStrategys = pricingStrategys;
	}
	
	public PricingStrategy getPricingStrategy() {
		return pricingStrategy;
	}

	public void setPricingStrategy(PricingStrategy pricingStrategy) {
		this.pricingStrategy = pricingStrategy;
	}
	
	public Trade getTrade() {
		return trade;
	}

	public void setTrade(Trade trade) {
		this.trade = trade;
	}

	public TradeDao getTradeDao() {
		return tradeDao;
	}

	public void setTradeDao(TradeDao tradeDao) {
		this.tradeDao = tradeDao;
	}
	
	public List<Trade> getTrades() {
		return trades;
	}

	public void setTrades(List<Trade> trades) {
		this.trades = trades;
	}
	
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	public List<AppuserSoftwareBalance> getAppuserSoftwareBalances() {
		return appuserSoftwareBalances;
	}

	public void setAppuserSoftwareBalances(List<AppuserSoftwareBalance> appuserSoftwareBalances) {
		this.appuserSoftwareBalances = appuserSoftwareBalances;
	}
	
	public AppuserSoftwareBalanceDao getAppuserSoftwareBalanceDao() {
		return appuserSoftwareBalanceDao;
	}

	public void setAppuserSoftwareBalanceDao(AppuserSoftwareBalanceDao appuserSoftwareBalanceDao) {
		this.appuserSoftwareBalanceDao = appuserSoftwareBalanceDao;
	}

}
